﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.EShop.Bll;
using Runda.EShop.Common.Entity;
using System.Data;
using Runda.EShop.Common.Utility;
using System.Net;
using Runda.EShop.Common.Component;

namespace Runda.EShop.Web.Customer
{
    public partial class ProductDetail : BasePage
    {
        public Guid ProductID
        {
            get
            {
                if (Request.QueryString["ProductID"] == null) return Guid.Empty;
                return new Guid(Request.QueryString["ProductID"]);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MasterDataBll bll = new MasterDataBll();
                BasProductEntity entity = bll.Get<BasProductEntity>(ProductID);

                if (entity != null)
                {
                    //Server.MapPath
                    if (RemoteFileExists("http://oos.rundamedical.com:9090/Images/Product/" + entity.ProductCode + ".jpg")) { imgProduct.ImageUrl = "../Images/Product/" + entity.ProductCode + ".jpg"; }
                    else { imgProduct.ImageUrl = "../Images/Product/blank.jpg"; }
                    //imgProduct.ImageUrl = "../Images/Product/201271917223.jpg";
                    ltlProductName.Text = entity.ProductName;
                    ltlProductCode.Text = entity.ProductCode;
                    ltlAbbrName.Text = entity.Description; ;
                    ltlStandard.Text = entity.Standard; 
                    ltlUnit.Text = entity.Unit;
                    ltlAlias.Text = entity.Alias;
                    ltlTrademark.Text = entity.Trademark;

                    if (entity.RegCertificateDate == DateTime.MinValue)
                    {
                        btnAddCart.Visible = false;
                    }
                }

                GetProductOrderHistory();

                GetProductRelation(); 
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            //加订购控件
            OrderProductControl ucOrder = null;
            if (base.User.Identity.LoginUser.EntType == (int)EnumHelper.EnterpriseType.Terminal)
            {
                ucOrder = (OrderProductControl)Page.LoadControl("~/UserControl/OrderDetailTerminal.ascx");
            }
            else
            {
                ucOrder = (OrderProductControl)Page.LoadControl("~/UserControl/OrderDetailAgent.ascx");
            }
            MasterDataBll bll = new MasterDataBll();
            BasProductEntity entity = bll.Get<BasProductEntity>(ProductID);
            ucOrder.ProductCode = entity.ProductCode;
            ucOrder.ID = "ucOrder";
            phOrder.Controls.Add(ucOrder);
        }

        private bool RemoteFileExists(string fileUrl)      {     
            bool result = false;//下载结果            
            WebResponse response = null;            
            try  
            {
                WebRequest req = WebRequest.Create(fileUrl); 
                response = req.GetResponse();
                result = response == null ? false : true;            }            
            catch (Exception ex)
                {                
                    result = false;            
                }            
            finally            
                { if (response != null)  {  response.Close(); }            }            
            return result;        
        }
        /// <summary>
        /// 绑定购买过的产品
        /// </summary>
        private void GetProductOrderHistory() 
        {
            BizOrderDetailBll bll = new BizOrderDetailBll();
            int RecordCount = 0;
            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = null;
            parm = new SqlDbParameter();
            parm.ColumnName = "[CustomerID]";
            parm.ColumnType = DbType.Guid;
            parm.ParameterName = "@CustomerID";
            parm.ParameterValue = base.User.Identity.LoginUser.UserID;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            parm = new SqlDbParameter();
            parm.ColumnName = "[ProductID]";
            parm.ColumnType = DbType.Guid;
            parm.ParameterName = "@ProductID";
            parm.ParameterValue = ProductID;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            parm = new SqlDbParameter();
            parm.ColumnName = "[ProductID]";
            parm.ColumnType = DbType.Int32;
            parm.ParameterName = "@ProductID";
            parm.ParameterValue = 10;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Top;
            parms.Add(parm);

            DataTable dt = bll.GetOrderDetail(parms, "OrderDate DESC", 10, 0, out RecordCount);
            gvOrderDetailHistory.DataSource = dt;
            gvOrderDetailHistory.DataBind();
        }

        /// <summary>
        /// 关联产品
        /// </summary>
        private void GetProductRelation()
        {
            BasProductRelationBll bll = new BasProductRelationBll();
            DataTable dt = bll.GetRelationProduct(ProductID);

            gvRelationProduct.DataSource = dt;
            gvRelationProduct.DataBind();
        }

        protected void btnAddCart_Click(object sender, ImageClickEventArgs e)
        {
            OrderProductControl ucOrder = (OrderProductControl)phOrder.FindControl("ucOrder");
            List<BizShopCartEntity> list = ucOrder.ProductList;

            //当库存数量不为零时，订购数量不能大于库存数量
            if (base.User.Identity.LoginUser.EntType == (int)EnumHelper.EnterpriseType.Terminal)
            {
                bool flag = true;
                foreach (BizShopCartEntity entity in list)
                {
                    if (entity.Inventory != 0 && entity.Inventory < entity.Quantity)
                    {
                        flag = false;
                        break;
                    }
                }

                if (!flag)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "error", "alert('订购数量不能大于库存数量');", true);
                    return;
                }
            }

            BizShopCartBll bll = new BizShopCartBll();
            bll.BatchInsert(list);

            ClientScript.RegisterStartupScript(this.GetType(), "success", "window.opener=null;top.location.href='AddToShopcart.aspx'", true);
        }

        protected void gvRelationProduct_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView dv = e.Row.DataItem as DataRowView;
                Button btnOrder = e.Row.FindControl("btnOrder") as Button;

                if (Convert.ToInt32(dv["IsCart"].ToString()) == 1)
                {
                    btnOrder.Visible = false;
                }
            }
        }

        protected void gvRelationProduct_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "order")
            {
                Guid ProductID = new Guid(e.CommandArgument.ToString());

                BizShopCartEntity entity = new BizShopCartEntity();
                entity.CustomerID = base.User.Identity.LoginUser.UserID;
                entity.ProductID = ProductID;
                entity.Quantity = 0;
                entity.CreatedAt = DateTime.Now;
                entity.Deleted = false;
                BizShopCartBll bll = new BizShopCartBll();
                bll.AddProductToShopcart(entity);

                GetProductRelation();
            }
        }
    }
}